package fr.ydelouis.swipelistviewsample;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import android.app.Activity;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;
import fr.ydelouis.stdlvsample.R;
import fr.ydelouis.swipelistviewsample.adapter.NotificationAdapter;
import fr.ydelouis.swipelistviewsample.element.NotificationItem;
import fr.ydelouis.swipelistviewsample.helper.Utinities;
import fr.ydelouis.widget.SwipeToDeleteListView;
import fr.ydelouis.widget.SwipeToDeleteListView.OnItemDeletedListener;

public class NotificationActivity extends Activity implements
		OnItemDeletedListener, AdapterView.OnItemLongClickListener,
		AdapterView.OnItemClickListener {

	private SwipeToDeleteListView listView;
	private NotificationAdapter adapter;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_list);

		notifiItems = new ArrayList<NotificationItem>();
		adapter = new NotificationAdapter(this, notifiItems);

		listView = (SwipeToDeleteListView) findViewById(R.id.list);
		listView.setOnItemDeletedListener(this);
		listView.setOnItemClickListener(this);
		listView.setOnItemLongClickListener(this);
		listView.setAdapter(adapter);

		new LongGetNotifi().execute();
	}

	@Override
	public void onItemDeleted(SwipeToDeleteListView listView, int position) {
		notifiItems.remove(position);
		adapter.notifyDataSetChanged();
	}

	@Override
	public boolean onItemLongClick(AdapterView<?> parent, View view,
			int position, long id) {
		Toast.makeText(this, position + " has been long clicked",
				Toast.LENGTH_SHORT).show();
		return true;
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		Toast.makeText(this, position + " has been clicked", Toast.LENGTH_SHORT)
				.show();
	}

	private class LongGetNotifi extends AsyncTask<Void, Void, Void> {

		@Override
		protected void onPreExecute() {
		}

		@Override
		protected void onProgressUpdate(Void... values) {
		}

		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub

			getNotifi();
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);

			adapter.notifyDataSetChanged();
			// Log.d("time", System.currentTimeMillis() +"");
		}
	}

	ArrayList<NotificationItem> notifiItems;
	int numMsg;
	int numMissCall;

	public void getNotifi() {
		String str_msg;
		Date alsoNow;

		alsoNow = Calendar.getInstance().getTime();

		numMsg = 0;
		Uri mSmsinboxQueryUri = Uri.parse("content://sms/inbox");
		Cursor cursor1 = getContentResolver().query(
				mSmsinboxQueryUri,
				new String[] { "_id", "thread_id", "address", "person", "date",
						"body", "type", "read", "status" }, null, null, null);

		String[] columns = new String[] { "address", "person", "date", "body",
				"type", "read", "status", "_id", "thread_id" };

		if (cursor1.getCount() > 0) {

			while (cursor1.moveToNext()) {

				String address = cursor1.getString(cursor1
						.getColumnIndex(columns[0]));

				String name = cursor1.getString(cursor1
						.getColumnIndex(columns[1]));

				String d = cursor1
						.getString(cursor1.getColumnIndex(columns[2]));

				Date date = new Date(cursor1.getLong(cursor1
						.getColumnIndex(columns[2])));

				String formattedDate = new SimpleDateFormat("dd/MM/yyyy HH:MM")
						.format(date);

				String msg = cursor1.getString(cursor1
						.getColumnIndex(columns[3]));
				String type = cursor1.getString(cursor1
						.getColumnIndex(columns[4]));

				String read = cursor1.getString(cursor1
						.getColumnIndex(columns[5]));

				String status = cursor1.getString(cursor1
						.getColumnIndex(columns[6]));

				String id = cursor1.getString(cursor1
						.getColumnIndex(columns[7]));

				String thread_id = cursor1.getString(cursor1
						.getColumnIndex(columns[8]));

				String nameContact;
				if (read.equals("0")) {

					if (address.contains("+")) {
						nameContact = Utinities.getContactName(
								getApplicationContext(), address);

					} else {
						nameContact = address;

					}

					int diffDate = (int) Utinities.getDateDiffString(date,
							alsoNow);

					// if (SettingsHelper.isHideContentSMS(mContext)) {
					// msg = "You have new unread message";
					// }
					switch (diffDate) {
					case 0:
						notifiItems.add(new NotificationItem(id, formattedDate
								.split(" ")[1] + " " + "Today", nameContact,
								msg, thread_id, NotificationItem.SMS,
								notifiItems.size()));
						break;

					case 1:
						notifiItems.add(new NotificationItem(id, formattedDate
								.split(" ")[1] + " " + "Yesterday",
								nameContact, msg, thread_id,
								NotificationItem.SMS, notifiItems.size()));
						break;
					case 2:
						notifiItems.add(new NotificationItem(id, formattedDate
								.split(" ")[1] + " " + "Two days ago",
								nameContact, msg, thread_id,
								NotificationItem.SMS, notifiItems.size()));
						break;
					default:
						notifiItems.add(new NotificationItem(id, formattedDate
								.split(" ")[1]
								+ " "
								+ formattedDate.split(" ")[0], nameContact,
								msg, thread_id, NotificationItem.SMS,
								notifiItems.size()));
						break;
					}

					numMsg++;
					// Log.d("Kai", address + " : " + nameContact + " " +
					// address);

				}
			}

		}

		numMissCall = 0;
		// missCallItems = new ArrayList<MissCallItem>();
		String callLogID, callNumber, callDate, callType, isCallNew, callName;
		final String[] projection = null;
		final String selection = null;
		final String[] selectionArgs = null;
		final String sortOrder = android.provider.CallLog.Calls.DATE + " DESC";
		Cursor cursor = null;
		try {
			cursor = getContentResolver().query(
					Uri.parse("content://call_log/calls"), projection,
					selection, selectionArgs, sortOrder);
			while (cursor.moveToNext()) {
				callLogID = cursor.getString(cursor
						.getColumnIndex(android.provider.CallLog.Calls._ID));
				callNumber = cursor.getString(cursor
						.getColumnIndex(android.provider.CallLog.Calls.NUMBER));

				Date dateCall = new Date(cursor.getLong(cursor
						.getColumnIndex(android.provider.CallLog.Calls.DATE)));
				callDate = new SimpleDateFormat("dd/MM/yyyy HH:MM ")
						.format(dateCall);

				callType = cursor.getString(cursor
						.getColumnIndex(android.provider.CallLog.Calls.TYPE));
				isCallNew = cursor.getString(cursor
						.getColumnIndex(android.provider.CallLog.Calls.NEW));

				if (Integer.parseInt(callType) == android.provider.CallLog.Calls.MISSED_TYPE
						&& Integer.parseInt(isCallNew) > 0) {

					int checkExit = checkMissCallExit(callNumber, notifiItems);
					if (checkExit != -1) {

						NotificationItem item = notifiItems.get(checkExit);
						item.setSize();
						item.setName("New number (" + item.getSize() + ")");

					} else {

						numMissCall++;

						int diffDate = (int) Utinities.getDateDiffString(
								dateCall, alsoNow);

						// Log.d("Kai", "Call: " + diffDate);

						switch (diffDate) {
						case 0:
							callDate = callDate.split(" ")[1] + " " + "Today";
							break;
						case 1:
							callDate = callDate.split(" ")[1] + " "
									+ "Yesterday";
							break;
						case 2:
							callDate = callDate.split(" ")[1] + " "
									+ "Two days ago";
							break;
						default:
							callDate = callDate.split(" ")[1] + " "
									+ callDate.split(" ")[0];
							break;
						}

						if (!Utinities.getContactName(getApplicationContext(),
								callNumber).equals(callNumber)) {
							callName = Utinities.getContactName(
									getApplicationContext(), callNumber);
						} else {
							callName = "New number";
						}
						notifiItems
								.add(new NotificationItem(callLogID, callDate,
										callName, callNumber, "",
										NotificationItem.MISS_CALL, notifiItems
												.size()));
					}

					// .add(new MissCallItem(callLogID, getContactName(
					// getApplicationContext(), callNumber),
					// callNumber, callDate, isCallNew));
					//
					// noti
				}
			}
		} catch (Exception ex) {

		} finally {
			if (cursor != null) {
				cursor.close();
			}
		}

		if (numMissCall > 0 || numMsg > 0) {

			// NotifiExoAdapter notifiExoAdapter = new NotifiExoAdapter(
			// getApplicationContext(), notifiItems, this);
			// lvNotifi.setAdapter(notifiExoAdapter);
		}

		// if (isShowToolbar) {
		// isShowToolbar = false;
		// llToolbar.setVisibility(View.GONE);
		// }
	}

	public int checkMissCallExit(String number,
			ArrayList<NotificationItem> notifis) {
		for (int i = 0; i < notifis.size(); i++) {
			NotificationItem item = notifis.get(i);
			if (item.getType() == NotificationItem.MISS_CALL
					&& item.getBody().equals(number)) {
				return i;
			}
		}
		return -1;
	}
}
